//
//  HYOUGiftHomeCollectionCell.m
//  BestGift
//
//  Created by 温晓宇 on 16/1/5.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "HYOUGiftHomeCollectionCell.h"
#import "HYOUHomeTableViewCell.h"
#import "HYOUHeadScrollView.h"
#import "HYOUDownScrollViewCell.h"
@interface HYOUGiftHomeCollectionCell ()<UITableViewDataSource, UITableViewDelegate,HYOUDownScrollViewCellDelegate,HYOUHeadScrollViewDelegate>

@property(nonatomic, retain) HYOUBaseTableView *myTableView;
@property(nonatomic, retain) NSMutableArray *allArray;

@property(nonatomic, retain) NSMutableArray *scrollArray;
@property(nonatomic, retain) NSMutableArray *imageArray;

@property(nonatomic, retain) HYOUHeadScrollView *headView;

@property(nonatomic,assign)NSInteger nextPage;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉

@end

@implementation HYOUGiftHomeCollectionCell
//-(void)dealloc{
//    [_delegate release];
//    [_myTableView release];
//    [_allArray release];
//    [_scrollArray release];
//    [_imageArray release];
//    [_headView release];
//    [super dealloc];
//}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubViews];
    }
    return self;
}
- (void)createSubViews{
    self.myTableView = [[HYOUBaseTableView alloc]initWithFrame:CGRectMake(0, 30, WIDTH, HEIGHT - 140) style:UITableViewStylePlain];
//    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.contentView addSubview:self.myTableView];
    [_myTableView release];
    
    self.headView = [[HYOUHeadScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    self.headView.delegate = self;
    self.myTableView.tableHeaderView = self.headView;
    [_headView release];
    
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.myTableView registerClass:[HYOUHomeTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[HYOUDownScrollViewCell class] forCellReuseIdentifier:@"down"];
    
#pragma makr -- 审核 刷新加载
    self.isUpLoading = NO;
    
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    /***************CELL解析************/
    self.allArray = [NSMutableArray array];
//    NSString *cellUrl = @"http://api.liwushuo.com/v2/channels/104/items?limit=20&ad=2&gender=2&offset=0&generation=2";
//    [AppTools finalAFNWithURLString:cellUrl parameters:nil successAFNBlock:^(id resuposeObject) {
//        NSMutableDictionary *bigDic = resuposeObject;
//        NSMutableDictionary *data = [bigDic objectForKey:@"data"];
//        NSMutableArray *items = [data objectForKey:@"items"];
//        for (NSDictionary *dic in items) {
//            HYOUOneCellModel *cellModel = [[HYOUOneCellModel alloc] init];
//            [cellModel setValuesForKeysWithDictionary:dic];
//            [self.allArray addObject:cellModel];
////            NSLog(@"%ld", self.allArray.count);
//        }
//        [self.myTableView reloadData];
//    }];
    /**************轮播图**************/
    self.scrollArray = [NSMutableArray array];
    NSString *maxScroll = @"http://api.liwushuo.com/v2/banners";
    [AppTools finalAFNWithURLString:maxScroll parameters:nil successAFNBlock:^(id resuposeObject) {
        NSMutableDictionary *bigDic = resuposeObject;
        NSMutableDictionary *dic = [bigDic objectForKey:@"data"];
        NSMutableArray *array = [dic objectForKey:@"banners"];
        for (NSDictionary *dic in array) {
            HYOUHeadScroll *headModel = [[HYOUHeadScroll alloc]init];
            [headModel setValuesForKeysWithDictionary:dic];
            [self.scrollArray addObject:headModel];
//            [headModel release];
        }
        self.headView.allArray = self.scrollArray;
        [self.myTableView reloadData];
    }];


}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return self.allArray.count;
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section == 0) {
//        HYOUHeadScrollView *cell = [tableView dequeueReusableCellWithIdentifier:@"head"];
//        if (self.scrollArray.count != 0 ) {
//                    cell.allArray = self.scrollArray;
//        }
//        return cell;
    if (indexPath.section == 0){
        HYOUDownScrollViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"down"];
        cell.myDelegate = self;
        return cell;
    }else{
        HYOUHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        HYOUOneCellModel *model = [self.allArray objectAtIndex:indexPath.row];
        cell.model = model;
        return cell;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 100;
    }
//    if (indexPath.section == 0) {
//        return 200;
//    }
    return 150;
}
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 10;
//}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HYOUOneCellModel *model = [self.allArray objectAtIndex:indexPath.row];
    [self.delegate showHomeCellWebView:model.content_url Image:model.cover_image_url title:model.title];
}
-(void)showDownWeb:(NSString *)url{
    [self.delegate showDownScroll:url];
}
-(void)showDownTopic:(NSString *)url{
    [self.delegate showDownTopic:url];
}

#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block HYOUGiftHomeCollectionCell *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myTableView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block HYOUGiftHomeCollectionCell *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.myTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage += 20;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
    }];
}





#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //****参数cursor的值: 第一页默认为0，下一页就是请求下来数据中next_cursor的值
    //****参数count 的值: 是指定一页显示多少条数据
    
    //    NSString *url_string = [NSString stringWithFormat:@"https://api.weibo.com/2/friendships/friends.json?uid=5626008324&access_token=2.00klJkIGGZulFC50e2f524e40S8nlw&cursor=%ld&count=2",nextCursor];
//    if (self.isUpLoading == YES) {
//        [self.scrollArray removeAllObjects];
//    }
//    NSString *maxScroll = @"http://api.liwushuo.com/v2/banners";
//    [AppTools finalAFNWithURLString:maxScroll parameters:nil successAFNBlock:^(id resuposeObject) {
//        NSMutableDictionary *bigDic = resuposeObject;
//        NSMutableDictionary *dic = [bigDic objectForKey:@"data"];
//        NSMutableArray *array = [dic objectForKey:@"banners"];
//        for (NSDictionary *dic in array) {
//            HYOUHeadScroll *headModel = [[HYOUHeadScroll alloc]init];
//            [headModel setValuesForKeysWithDictionary:dic];
//            [self.scrollArray addObject:headModel];
//        }
//                self.headView.allArray = self.scrollArray;
//        [self.myTableView reloadData];
//    }];
    
    
    NSString *url_string = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/104/items?generation=2&gender=2&limit=20&ad=2&offset=%ld",(long)nextCursor];
    
//    NSLog(@" page = %ld\n url = %@", self.nextPage, url_string);
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
    
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.allArray removeAllObjects];
//            [self.scrollArray removeAllObjects];
        }
        NSMutableDictionary *bigDic = responseObject;
        NSMutableDictionary *data = [bigDic objectForKey:@"data"];
        NSMutableArray *items = [data objectForKey:@"items"];
        for (NSDictionary *dic in items) {
            HYOUOneCellModel *cellModel = [[HYOUOneCellModel alloc] init];
#pragma mark -- 审核 kvc
            [cellModel setValuesForKeysWithDictionary:dic];
//            [[HYOUSingleton shareDataSingleton] insertHomeCellIntoTable:cellModel];
            [self.allArray addObject:cellModel];
            //            NSLog(@"%ld", self.allArray.count);
        }

        
        
        [self.myTableView footerEndRefreshing];
        [self.myTableView headerEndRefreshing];
        [self.myTableView reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}

-(void)showHeadWeb:(NSString *)url{
    [self.delegate showHeadWeb:url];
}
-(void)showHeadDetail:(NSString *)targetId{
    [self.delegate showHeadDetail:targetId];
}
//-(void)headScroll{
//    NSString *maxScroll = @"http://api.liwushuo.com/v2/banners";
//    [AppTools finalAFNWithURLString:maxScroll parameters:nil successAFNBlock:^(id resuposeObject) {
//        NSMutableDictionary *bigDic = resuposeObject;
//        NSMutableDictionary *dic = [bigDic objectForKey:@"data"];
//        NSMutableArray *array = [dic objectForKey:@"banners"];
//        for (NSDictionary *dic in array) {
//            HYOUHeadScroll *headModel = [[HYOUHeadScroll alloc]init];
//            [headModel setValuesForKeysWithDictionary:dic];
//            [self.scrollArray addObject:headModel];
//        }
//        [self.myTableView reloadData];
////        [self.myTableView headerEndRefreshing];
//
//    }];
//}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
